import pandas as pd
from sqlalchemy import delete, desc, insert, select, text, update
from sqlalchemy.ext.asyncio import AsyncSession
from module_stock.entity.do.monthly_do import StockMonthly
from module_stock.entity.vo.monthly_vo import MonthlyModel, MonthlyPageQueryModel
from utils.page_util import PageUtil
from config.database  import engine
from utils.pd_util import AsyncORMConverter

class MonthlyDao:
    """
    股票月线模块数据库操作层
    """

    @classmethod
    async def get_monthly_detail_by_id(cls, db: AsyncSession, id: int):
        """
        根据id获取股票月线详细信息

        :param db: orm对象
        :param id: id
        :return: 股票月线信息对象
        """
        monthly_info = (
            (
                await db.execute(
                    select(StockMonthly)
                    .where(
                        StockMonthly.id == id
                    )
                )
            )
            .scalars()
            .first()
        )

        return monthly_info

    @classmethod
    async def get_monthly_detail_by_info(cls, db: AsyncSession, monthly: MonthlyModel):
        """
        根据股票月线参数获取股票月线信息

        :param db: orm对象
        :param monthly: 股票月线参数对象
        :return: 股票月线信息对象
        """
        monthly_info = (
            (
                await db.execute(
                    select(StockMonthly).where(
                    )
                )
            )
            .scalars()
            .first()
        )

        return monthly_info

    @classmethod
    async def get_monthly_list(cls, db: AsyncSession, query_object: MonthlyPageQueryModel, is_page: bool = False):
        """
        根据查询参数获取股票月线列表信息

        :param db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 股票月线列表信息对象
        """
        query = (
            select(StockMonthly)
            .where(
                StockMonthly.trade_date == query_object.trade_date if query_object.trade_date else True,
                StockMonthly.symbol == query_object.symbol if query_object.symbol else True,
                StockMonthly.open == query_object.open if query_object.open else True,
                StockMonthly.close == query_object.close if query_object.close else True,
                StockMonthly.high == query_object.high if query_object.high else True,
                StockMonthly.low == query_object.low if query_object.low else True,
                StockMonthly.vol == query_object.vol if query_object.vol else True,
                StockMonthly.amount == query_object.amount if query_object.amount else True,
                StockMonthly.amplitude == query_object.amplitude if query_object.amplitude else True,
                StockMonthly.pct_chg == query_object.pct_chg if query_object.pct_chg else True,
                StockMonthly.chg == query_object.chg if query_object.chg else True,
                StockMonthly.turn == query_object.turn if query_object.turn else True,
            )
            .order_by(StockMonthly.trade_date.desc())
        )
        monthly_list = await PageUtil.paginate(db, query, query_object.page_num, query_object.page_size, is_page)

        return monthly_list

    @classmethod
    async def get_all_monthly_pd(cls, db: AsyncSession, symbol:str):
        """
        获取所有股票月线信息

        :param db: orm对象
        :return: 股票信息集
        """
        query = (
            select(StockMonthly).where(StockMonthly.symbol == symbol).order_by(StockMonthly.trade_date.asc())
        )
        monthlys = (await db.execute(query)).scalars().all()
        monthly_df = pd.DataFrame(AsyncORMConverter._orms_to_dicts(monthlys))
        return monthly_df

    @classmethod
    async def get_all_monthly(cls, db: AsyncSession, symbol:str):
        """
        获取所有股票月线信息

        :param db: orm对象
        :return: 股票信息集
        """
        query = (
            select(StockMonthly).where(StockMonthly.symbol == symbol)
        )

        monthly_list = (await db.execute(query)).scalars().all()

        return monthly_list

    @classmethod
    async def add_monthly_dao(cls, db: AsyncSession, monthly: MonthlyModel):
        """
        新增股票月线数据库操作

        :param db: orm对象
        :param monthly: 股票月线对象
        :return:
        """
        db_monthly = StockMonthly(**monthly.model_dump(exclude={}))
        db.add(db_monthly)
        await db.flush()

        return db_monthly

    @classmethod
    async def edit_monthly_dao(cls, db: AsyncSession, monthly: dict):
        """
        编辑股票月线数据库操作

        :param db: orm对象
        :param monthly: 需要更新的股票月线字典
        :return:
        """
        await db.execute(update(StockMonthly), [monthly])

    @classmethod
    async def delete_monthly_dao(cls, db: AsyncSession, monthly: MonthlyModel):
        """
        删除股票月线数据库操作

        :param db: orm对象
        :param monthly: 股票月线对象
        :return:
        """
        await db.execute(delete(StockMonthly).where(
            StockMonthly.id.in_([monthly.id]) if monthly.id else True,
            StockMonthly.symbol == monthly.symbol if monthly.symbol else True
        ))

    @classmethod
    async def clear_monthly_dao(cls, db: AsyncSession):
        """
        清空股票月线数据库操作

        :param db: orm对象
        :return:
        """
        await db.execute(text("truncate table stock_monthly"))

    @classmethod
    async def batch_add_monthly_dao(cls, db: AsyncSession, monthlys: list[dict]):
        """
        批量新增股票基础信息数据库操作

        :param db: orm对象
        :param basics: 股票日线实体对象列表
        :return:
        """
        st = insert(StockMonthly).values(monthlys)
        await db.execute(st)

    @classmethod
    async def get_all_symbols(cls, db: AsyncSession):
        """
        获取所有股票代码

        :param db: orm对象
        :return: 股票代码集
        """
        query = (
            select(StockMonthly.symbol).distinct()
            .order_by(StockMonthly.symbol)
        )

        symbols = (await db.execute(query)).scalars().all()

        return symbols
    
    @classmethod
    async def batch_delete_monthly_dao(cls, db: AsyncSession, symbols, start_date = None):
        """
        批量删除股票月线信息数据库操作

        :param db: orm对象
        :param symbols: 股票代码集
        :return:
        """
        await db.execute(delete(StockMonthly).where(
            StockMonthly.symbol.in_(symbols) if symbols else True,
            StockMonthly.trade_date >= start_date if start_date else True
            )
        )

    @classmethod
    async def get_last_monthly_detail(cls, db: AsyncSession, symbol: str):
        """
        根据股票代码获取数据表最后一个月线信息

        :param db: orm对象
        :param symbol: 股票代码
        :return: 股票月线信息对象
        """
        weekly_info = (
            (
                await db.execute(
                    select(StockMonthly).where(
                        StockMonthly.symbol == symbol
                    ).order_by(desc(StockMonthly.trade_date)).limit(1)
                )
            )
            .scalars()
            .first()
        )

        return weekly_info